package com.lunesu.bjair;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;

public class BeijingAirActivity extends Activity {
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.main);

		// NO: we use a theme in the manifest, which will also work during startup
//		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// NO: webbrowser would show address bar
		//startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://iphone.bjair.info/")));
		
		WebView webview = (WebView)this.findViewById(R.id.webview1);
		webview.getSettings().setJavaScriptEnabled(true);
		//webview.loadData("<html><body>Updating...</body></html>", "text/html", null);
		webview.loadUrl("file:///android_asset/hello.html");
		
		// onStart will be called next
	}
	
	/** Show the specified HTML data in the webview.
	 * @param data the HTML data to show in the webview
	 */
	private void setWebviewContent(String data) {
		WebView webview = (WebView)findViewById(R.id.webview1);
		if (data.length() > 0) {
			String baseurl = getString(R.string.bjair_url);
			// TODO: get mimetype/encoding from http
			webview.loadDataWithBaseURL(baseurl, data, null, null, null);
		}
		else {
			// An error occured; show an error message
			webview.loadUrl("file:///android_asset/error.html");
		}
	}	
	
	@Override
	public void onStart() {
		super.onStart();
		
		final Handler handler = new Handler();
		final String baseurl = getString(R.string.bjair_url);
		final StringBuilder sb = new StringBuilder();
		
		// This 'delegate' will be invoked when the thread is done
		final Runnable runInUI = new Runnable() {
			@Override 
			public void run() { 
				// set the HTML content in the webview
				setWebviewContent(sb.toString());
			}
		};

		// Create a thread to update the AQI, and start it.
		new Thread() {
			@Override
			public void run() {
				int airquality = -1;
				try {
					// Get the air quality from HTTP and record the entire page into a string
					airquality = BeijingAirAppWidgetProvider.getAirQuality(baseurl, sb);
				} catch (IOException e) {
					//Log.e("error", "BeijingAirActivity.onStart", e);
				}
				// Execute the 'delegate' in the UI thread, so it can update the webview
				handler.post(runInUI);
				// Update the app-widget (apparently this works fine from this thread)
				BeijingAirAppWidgetProvider.updateWidget(BeijingAirActivity.this, airquality);
			}
		}.start();
	}
}
